//
//  WbComposeController.swift
//  Weibo
//
//  Created by HH on 16/12/10.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit
import SVProgressHUD

class WbComposeController: UIViewController {
    
    
    //发送按钮
    lazy private var sendBtn:UIButton = {
       
        let btn = UIButton()
        
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(UIColor.lightGray, for: .disabled)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.addTarget(self, action: #selector(sendAction(sender:)), for: .touchUpInside)
        
        btn.size = CGSize(width: 45, height: 30)
        
        return btn
        
    }()
    
    //textView
    lazy private var textView:WbComposeTextView = {
        
        let textView = WbComposeTextView()
        
        textView.delegate = self
        
        textView.keyboardDismissMode = .onDrag
        
        textView.alwaysBounceVertical = true
        //去除纠错提示
        textView.autocorrectionType = .no
        
        textView.font = UIFont.systemFont(ofSize: 15)
        return textView
        
    }()
    
    //标题Label
    lazy private var titleLabel:UILabel = {
       
        let label = UILabel()
        
        label.font = UIFont.systemFont(ofSize: 17)
        
        let name = WbUserAccountViewModel.sharedUserAccount.userInfo?.name
        
        let title = "发微博\n\(name!)"
        
        let range = (title as NSString).range(of: name!)
        
        let attributedString = NSMutableAttributedString(string: title)
        
        attributedString.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12),
                                        NSForegroundColorAttributeName:UIColor.lightGray], range: range)
        
        label.attributedText = attributedString
        
        label.numberOfLines = 0
        
        label.textAlignment = .center
        
        label.sizeToFit()
        
        return label
        
    }()
    
    //composeToolBar
    lazy private var composeToolBar:WbComposeToolBar = WbComposeToolBar()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        // Do any additional setup after loading the view.
    }
    
    //布局导航栏
    private func setupNavUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, selector: #selector(cancelAction(sender:)), color: UIColor.black)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        
        navigationItem.titleView = titleLabel
        
        navigationItem.rightBarButtonItem?.isEnabled = false
        
//        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", imageName: nil, backgroundImageName: "tabbar_compose_button", target: self, selector: #selector(cancelAction(sender:)), color: UIColor.blue)
    }
    
    @objc private func sendAction(sender:UIButton){
        
        SVProgressHUD.show(withStatus: "发送中...")
        
        
        WbNetworking.sharedTools.updateStatuses(status: textView.text, visible: 0, lat: 0, long: 0) { (isScuess) in
            
//            SVProgressHUD.dismiss()
            
            if isScuess{
                
                SVProgressHUD.showSuccess(withStatus: "微博发送成功!")
                
                
                print("发送微博成功")
                
            }else{
                
                SVProgressHUD.showError(withStatus: "发送失败!")
                print("发送微博失败")
            }
            
            
        }
        
    }
    
    //取消按钮点击事件
    @objc private func cancelAction(sender:UIButton){
        
 
        textView.resignFirstResponder()
        
        dismiss(animated: true, completion: nil)
        
       
    }
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.white
        
        setupNavUI()
     
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        
        
        
        textView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(marign)
            make.right.equalToSuperview().offset(-marign)
        }
        
        composeToolBar.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(35)
        }
        
        
        composeToolBar.callBack = {[weak self] (tag)->() in
            
            
            switch tag {
            case composeToolBarType.picture.hashValue:
                print("图片")
                self?.didSelectedPicture()
                
            case composeToolBarType.mention.hashValue:
                print("@")
            case composeToolBarType.trend.hashValue:
                print("话题")
            case composeToolBarType.emoticon.hashValue:
                print("表情")
            case composeToolBarType.add.hashValue:
                print("加号")
            default:
                break
            }
            
        }
        
        //改变composeTool的frame,利用系统的通知
        changeToolBarFrame()
 
    }
    
    
    //监听系统发送的通知,查看键盘的frame的变化
    private func changeToolBarFrame(){
        
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil, queue: OperationQueue.main) { (notification) in
            //            print(notification)
            
            let userInfo = notification.userInfo
            
            let rect = (userInfo?["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
            
            let duration = (userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
            //            print(rect.size.height - ScreenHeight)
            self.composeToolBar.snp.updateConstraints({ (make) in
                make.bottom.equalToSuperview().offset(rect.origin.y - ScreenHeight)
            })
            
            
            UIView.animate(withDuration: duration, animations: {
                self.view.layoutIfNeeded()
            })
            
            //            if self.composeToolBar.y == ScreenHeight - self.composeToolBar.height{
            //
            //                self.composeToolBar.y = rect.origin.y - self.composeToolBar.height
            //            }else{
            //
            //                self.composeToolBar.y = ScreenHeight - self.composeToolBar.height
            //            }
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    deinit {
        //移除观察者
        NotificationCenter.default.removeObserver(self)
    }

}

//composeTool的按钮点击事件
extension WbComposeController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //选择图片按钮
    func didSelectedPicture(){
        
        let imagePickerController = UIImagePickerController()
        
        imagePickerController.delegate = self
        
        imagePickerController.allowsEditing = true
        
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            
            imagePickerController.sourceType = .camera
            
        }else{
            imagePickerController.sourceType = .photoLibrary
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.front){
            
            print("前置摄像头可以用")
        }else if UIImagePickerController.isCameraDeviceAvailable(.rear){
            
            print("后置摄像头可以用")
        }else{
            
            print("相机不可用")
        }
        
        present(imagePickerController, animated: true, completion: nil)
    }
    
    
    
    //选择图片后会掉这个方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        let currentImage = scaleImage(scaleWidth: 200, image: image)
        
        print(currentImage)
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    //压缩图片
    private func scaleImage(scaleWidth:CGFloat,image:UIImage)->UIImage{
        
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        
        UIGraphicsBeginImageContext(image.size)
        
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return currentImage!
    }
    
    
    
    //取消选择图片会调这个方法
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        picker.dismiss(animated: true, completion: nil)
    }
    
}



//textView的代理方法
extension WbComposeController:UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        
        
        //设置首行缩进
//        let paragraphStyle = NSMutableParagraphStyle()
//        
//        paragraphStyle.lineSpacing = 5
//        
//        paragraphStyle.maximumLineHeight = 60
//        
//        paragraphStyle.firstLineHeadIndent = 20.0
//        
//        paragraphStyle.alignment = .justified
//        
//        let attributes = [NSParagraphStyleAttributeName:paragraphStyle,
//                          NSFontAttributeName:UIFont.systemFont(ofSize: 14)]
//        
//        textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes)
    }
}
